<template>
  <div class="comment-management">
    <div class="header">
      <h1>评论管理</h1>
      <el-button type="primary" @click="handleAdd">新增评论</el-button>
    </div>

    <div class="search-container">
      <el-form :inline="true" label-width="80px">
        <el-form-item label="景区名称">
          <el-input v-model="searchSightName" placeholder="请输入景区名称" clearable style="width: 160px;"
            @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input v-model="searchKeyword" placeholder="请输入评论内容关键词搜索" style="width: 250px" clearable
            @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" style="margin-left: 10px">搜索</el-button>
          <el-button @click="handleReset" style="margin-left: 10px">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <el-table :data="commentList" style="width: 100%" border size="medium" :header-cell-style="{ fontWeight: 'bold' }"
        :cell-style="{ height: '60px' }">
        <el-table-column prop="commentId" label="评论ID" width="100" align="center" />
        <el-table-column prop="userId" label="用户ID" width="100" align="center" />
        <el-table-column label="景区名称" width="180" align="center">
          <template #default="scope">
            {{ getSightNameById(scope.row.sightId) || '未知景区' }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" min-width="220" align="left" show-overflow-tooltip />
        <el-table-column prop="likeCount" label="点赞数" width="80" align="center" />
        <el-table-column prop="replyCount" label="回复数" width="80" align="center" />
        <el-table-column prop="replyToCommentId" label="回复评论ID" width="110" align="center">
          <template #default="scope">
            {{ scope.row.replyToCommentId || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="formData" label-width="90px">
        <el-form-item label="用户ID">
          <el-input v-model.number="formData.userId" placeholder="请输入用户ID" type="number" />
        </el-form-item>
        <el-form-item label="景区名称" prop="sightId" :rules="[{ required: true, message: '请选择景区', trigger: 'blur' }]">
          <el-select v-model.number="formData.sightId" placeholder="请选择景区">
            <el-option v-for="sight in sightList" :key="sight.sightId" :label="sight.name" :value="sight.sightId" />
          </el-select>
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input v-model="formData.content" placeholder="请输入评论内容" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="回复评论ID">
          <el-input v-model.number="formData.replyToCommentId" placeholder="如为回复请填写评论ID" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getComments, addComment, updateComment, deleteComment } from '@/views/api/comment'
import { getSightList } from '@/views/api/sight'

// 数据列表
const commentList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const searchSightName = ref('')
// 景区列表
const sightList = ref([])

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增评论')
const formData = reactive({
  commentId: null,
  userId: '',
  sightId: '',
  content: '',
  replyToCommentId: ''
})

// 重置表单
const resetForm = () => {
  formData.commentId = null
  formData.userId = ''
  formData.sightId = ''
  formData.content = ''
  formData.replyToCommentId = ''
}

// 获取景区列表
const getSights = async () => {
  try {
    const response = await getSightList()
    // 确保sightList是数组类型
    if (response.data && response.data.data && Array.isArray(response.data.data.items)) {
      // 正确处理API返回的数据结构: data.data.items
      sightList.value = response.data.data.items
    } else if (response.data && Array.isArray(response.data.data)) {
      // 处理可能的分页结构
      sightList.value = response.data.data
    } else if (Array.isArray(response.data)) {
      sightList.value = response.data
    } else {
      console.warn('景区数据格式不符合预期:', response)
      sightList.value = []
    }
  } catch (error) {
    ElMessage.error('获取景区列表失败')
    console.error('获取景区列表失败:', error)
    sightList.value = []
  }
}

// 根据景区ID获取景区名称
const getSightNameById = (id) => {
  // 安全检查，确保sightList是数组
  if (!Array.isArray(sightList.value)) {
    console.warn('sightList不是有效的数组')
    return '未知景点'
  }
  // 根据API返回的实际字段名进行匹配 (sightId)
  const sight = sightList.value.find(item => item.sightId === id)
  return sight ? sight.name : '未知景点'
}

// 获取评论列表
const getCommentList = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    }
    if (searchSightName.value && searchSightName.value.trim() !== '') {
      params.sightName = searchSightName.value.trim()
    }
    const response = await getComments(params)
    console.log('获取评论列表成功:', response.data)
    commentList.value = response.data.data.list || []
    total.value = response.data.data.total || 0
  } catch (error) {
    ElMessage.error('获取评论列表失败')
    console.error('获取评论列表失败:', error)
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置为第一页
  getCommentList()
}

// 重置搜索
const handleReset = () => {
  searchKeyword.value = ''
  searchSightName.value = ''
  currentPage.value = 1
  getCommentList()
}

// 新增评论
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增评论'
  dialogVisible.value = true
}

// 编辑评论
const handleEdit = (row) => {
  // 深拷贝行数据以避免直接修改原始数据
  const rowData = { ...row }
  // 确保sightId是数字类型，与option的value类型匹配
  rowData.sightId = Number(rowData.sightId)
  Object.assign(formData, rowData)
  dialogTitle.value = '编辑评论'
  dialogVisible.value = true
}

// 删除评论
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除评论ID为 ${row.commentId} 的评论吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteComment(row.commentId)
    ElMessage.success('删除成功')
    getCommentList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除评论失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 修复：未填写回复用户ID时传null
    if (formData.replyToCommentId === '') {
      formData.replyToCommentId = null;
    }
    if (formData.commentId) {
      // 编辑操作
      await updateComment(formData.commentId, formData)
      ElMessage.success('更新成功')
    } else {
      // 新增操作
      await addComment(formData)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getCommentList()
  } catch (error) {
    ElMessage.error(formData.commentId ? '更新失败' : '新增失败')
    console.error('提交表单失败:', error)
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getCommentList()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  getCommentList()
}

// 初始加载数据
onMounted(async () => {
  // 先获取景区列表，再获取评论列表
  await getSights()
  getCommentList()
})
</script>

<style scoped>
.comment-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 增强表格样式 */
:deep(.el-table) {
  border: 0.5px solid #e8e8e8;
}

:deep(.el-table__header th.el-table__cell) {
  border-right: 0.5px solid #e8e8e8;
  border-bottom: 0.5px solid #e8e8e8;
}

:deep(.el-table__body td.el-table__cell) {
  border-right: 0.5px solid #e8e8e8;
  border-bottom: 0.5px solid #f0f0f0;
  padding: 12px 8px;
}

:deep(.el-table__body tr:hover > td.el-table__cell) {
  background-color: #f5f7fa;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>